package com.jingkong.component;

import com.jingkong.model.User;
import com.jingkong.util.EntityManagerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.*;
import javax.transaction.Transactional;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

@Component
public class UserComponent {
    
    @Autowired
    private EntityManagerFactory entityManagerFactory;

    public void addUserWithNativeQuery(String name,String email){
        EntityManager entityManager = null;
        EntityTransaction transaction = null;
        try{
            String sql = "insert into user(name,email) values(:name,:email)";
            entityManager = entityManagerFactory.createEntityManager();
            transaction = entityManager.getTransaction();
            transaction.begin();
            entityManager.createNativeQuery(sql).setParameter("name",name)
              .setParameter("email",email).executeUpdate();
            transaction.commit();
        }catch (Exception e){
            if (transaction != null && transaction.isActive()) {
                transaction.rollback(); // 回滚事务
            }
            e.printStackTrace();
        }finally {
            EntityManagerUtils.safelyClose(entityManager);
        }

    }

    public List<User> findUsersNative(){
        EntityManager entityManager = null;
        List<Objects[]> resultList = null;
        List<User> users = new ArrayList<>();
        try{
            entityManager = entityManagerFactory.createEntityManager();
            String sql = "SELECT id, name, email FROM user";
            Query nativeQuery = entityManager.createNativeQuery(sql);
            resultList = nativeQuery.getResultList();
            for(Object[] row:resultList){
                User u = new User();
                BigInteger bigInteger = Optional.ofNullable(row[0]).map(obj -> (BigInteger) obj).orElse(null);
                u.setId(bigInteger==null?null:bigInteger.longValue());
                u.setName(row[1]==null?null:row[1].toString());
                u.setEmail(Optional.ofNullable(row[2]).map(obj -> (String) obj).orElse(null));
                users.add(u);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
           EntityManagerUtils.safelyClose(entityManager);
        }
        return users;
    }
    
}
